/*
 * Author: 李波(Edwin Lee)
 * Date: 2024-07-07 23:30:18
 * FilePath: /code/C++/JsonCreate/main.cpp
 * LastEditTime: 2024-07-31 19:53:32
 * version: 1.0
 * Description: 
 */
// rapidjson/example/simpledom/simpledom.cpp`
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
#include <string>

using namespace std;
using namespace rapidjson;

string toString(Document& d)//自定义一个把document转换成string类型的函数
{
    StringBuffer buffer;
    Writer<StringBuffer> writer(buffer);
    d.Accept(writer);
    return buffer.GetString();
}

int main() 
{
    //例子一：构造一个object对象
    Document d;
    Document::AllocatorType& allocater = d.GetAllocator();
    d.SetObject();//整体是个OBJ对象

    /*
    //构造方法一：
    d.AddMember("id", 1001, allocater);
    d.AddMember("name", "zhangsan", allocater);
    d.AddMember("ismember", true, allocater);
    d.AddMember("job", Value(), allocater);//此处Value() == NULL,没有理解
    */

    //构造方法二：
    Value v;
    v.SetInt(1001);
    d.AddMember("id", v, allocater);
    v.SetString("zhangsan");
    d.AddMember("name", v, allocater);
    v.SetBool(true);
    d.AddMember("ismember", v, allocater);
    v.SetNull();
    d.AddMember("job", v, allocater);
    string str = toString(d);
    cout << str << endl;


    //例子二：构造一个array数组
    Document d1;
    Document::AllocatorType& alloc = d1.GetAllocator();
    d1.SetArray();//d1是一个数组
    d1.PushBack(1001, alloc);
    d1.PushBack(1002, alloc);
    d1.PushBack(1003, alloc);
    d1.PushBack(1004, alloc);
    str = toString(d1);
    cout << str << endl;

    //列子三：嵌套
    Document d2;
    Document::AllocatorType& alloc2 = d2.GetAllocator();
    d2.SetObject();
    d2.AddMember("id", 1001, alloc2);
    d2.AddMember("name", "lisi", alloc2);
    cout << toString(d2) << endl;
    Value v1;
    v1.SetObject();
    v1.AddMember("height", 188, alloc2);
    v1.AddMember("weight", "70kg", alloc2);
    d2.AddMember("examination", v1, alloc2);
    cout << toString(d2) << endl;
    Value v2;
    v2.SetArray();
    v2.PushBack(98, alloc2);
    v2.PushBack(88, alloc2);
    v2.PushBack(78, alloc2);
    d2.AddMember("scores", v2, alloc2);
    cout << toString(d2) << endl;
    return 0;
}